﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace SqlServer
{
    public partial class Form3 : Form
    {
        string sql;
        private SqlConnection connection;
        public string connectionString = "Data Source=localhost;Initial Catalog=C#sql;User ID=C#test;Password=123";
        public Form3(string dt) //接受Form2中传输的sql查询命令
        {
            InitializeComponent();
            sql = dt;
            connection = new SqlConnection(connectionString);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            using (SqlCommand command = new SqlCommand(sql, connection)) //根据传输的sql语句执行查询命令
            {
                try
                {
                    connection.Open();
                    DataTable dataTable = new DataTable();
                    SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connection);
                    dataAdapter.Fill(dataTable);
                    dataGridView1.DataSource = dataTable;
                    connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("查询数据失败，具体为:" + ex.Message, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
}
